<template>
  <div>
    <div class="title">
      
      <van-tabs @click="tabClick">
        <van-tab name="1" title="1">
          <div slot="title">1分钟</div>
        </van-tab>
        <van-tab name="5" title="5">
          <div slot="title">5分钟</div>
        </van-tab>
        <van-tab name="15" title="15">
          <div slot="title">15分钟</div>
        </van-tab>
        <van-tab name="30" title="30">
          <div slot="title">30分钟</div>
        </van-tab>
        <van-tab name="60" title="60">
          <div slot="title">60分钟</div>
        </van-tab>
        <van-tab name="240" title="240">
          <div slot="title">4小时</div>
        </van-tab>
        <span class="enlarge" >
          <img @click="zoomClick" src='../assets/s.png'>
        </span>
        <div id="echart" style="width:100%;height: 500px; padding-top: .6rem"></div>
      </van-tabs>
    </div>
  </div>
</template>

<script>
// 引入基本模板
import echarts from "echarts";
import axios from "axios";
// 引入柱状图组件
//require('echarts/lib/chart/line')
//require('echarts/lib/chart/bar')

// 引入提示框和title组件
//require('echarts/lib/component/tooltip')
//require('echarts/lib/component/title')

export default {
  name: "eCharts",
  data() {
    return {
      axios: {},
      myeChart: {},
      dataZoom: {
        direction: 1, //0 缩小， 1放大
        start: 50,
        end: 100,
        startValue: 0,
        endValue: 1
      }
    };
  },
  mounted() {
    this.axios = axios.create({
      //baseURL: process.env.BASE_URL,

      timeout: 12e5
    });

    this.axios.interceptors.response.use(
      response => {
        //console.log("aaa", response);
        return response.data;
      },
      error => {
        return Promise.reject(error);
      }
    );
    this.myeChart = echarts.init(document.getElementById("echart"));
    var that = this;
    this.myeChart.on('datazoom', function (params){
      
      //console.log(params);
      
      var startValue = that.myeChart.getModel().option.dataZoom[0].startValue;
      var endValue = that.myeChart.getModel().option.dataZoom[0].endValue;
      //获得起止位置百分比
      var start = that.myeChart.getModel().option.dataZoom[0].start;
      var end = that.myeChart.getModel().option.dataZoom[0].end;

      //console.log(start, end, startValue, endValue);

      that.dataZoom.start = start;
      that.dataZoom.end = end;
      that.dataZoom.startValue = startValue;
      that.dataZoom.endValue = endValue;
    

    })

    this.drawKline(1);
    //setTimeout(() => {
    //  this.drawKline('1');
    //}, 1500);
  },
  methods: {
    tabClick(name, title) {
      //console.log("dfsfs", name, title);
      let minutes = parseInt(title);

      this.drawKline(minutes);
    },
    async drawKline(minutes) {
      
      //console.log(this.myeChart.getOption())
      let data = await this.getData(minutes);
      this.myeChart.setOption(this.getOption(data));
      //window.onresize = myChart.resize;
    },

    splitData(rawData) {
      var categoryData = [];

      var values = [];
      var volumns = [];
      for (var i = 0; i < rawData.length; i++) {
        categoryData.push(this.formatTime(rawData[i].splice(0, 1)[0], "h:m"));
        //volumns.push(rawData[i].splice(4, 1)[0]);
        volumns.push(100);
        values.push(rawData[i]);
        
        
      }
      var ret = {
        categoryData: categoryData,
        values: values,
        volumns: volumns
      };
      //console.log(ret);
      return ret;
    },

    calculateMA(dayCount, data) {
      var result = [];
      for (var i = 0, len = data.values.length; i < len; i++) {
        if (i < dayCount) {
          result.push("-");
          continue;
        }
        var sum = 0;
        for (var j = 0; j < dayCount; j++) {
          sum += data.values[i - j][1];
        }
        result.push(sum / dayCount);
      }
      //console.log(dayCount)
      //console.log(data.values)
      //console.log(result)
      return result;
     
    },

    async getData(minutes) {
      let baseUrl = "http://ncx.aom2008.com/index/";
      let params = {
        pid: 6,
        num: 60,
        interval: minutes,
        isres: 1
      };
      let res;
      
      res = {
        topdata: {
          topdata: "1581514802",
          now: "1.0013",
          open: "1.0014",
          lowest: "1.0005",
          highest: "1.0040",
          close: "1.0017",
          state: "down"
        },
        items: [
          [1581511500, 1.0015, 1.0015, 1.0014, 1.0016],
          [1581511560, 1.0016, 1.0016, 1.0014, 1.0016],
          [1581511620, 1.0014, 1.0016, 1.0014, 1.0016],
          [1581511680, 1.0016, 1.0016, 1.0016, 1.0016],
          [1581511740, 1.0014, 1.0016, 1.0014, 1.0016],
          [1581511800, 1.0016, 1.0014, 1.0014, 1.0016],
          [1581511860, 1.0015, 1.0016, 1.0014, 1.0016],
          [1581511920, 1.0014, 1.0014, 1.0014, 1.0016],
          [1581511980, 1.0014, 1.0014, 1.0014, 1.0016],
          [1581512040, 1.0014, 1.0016, 1.0014, 1.0016],
          [1581512100, 1.0016, 1.0014, 1.0014, 1.0016],
          [1581512160, 1.0014, 1.0015, 1.0014, 1.0015],
          [1581512220, 1.0014, 1.0014, 1.0014, 1.0015],
          [1581512280, 1.0014, 1.0015, 1.0014, 1.0015],
          [1581512340, 1.0015, 1.0012, 1.0011, 1.0015],
          [1581512400, 1.0011, 1.0013, 1.0011, 1.0013],
          [1581512460, 1.0013, 1.0011, 1.0011, 1.0013],
          [1581512520, 1.0012, 1.0011, 1.0011, 1.0012],
          [1581512580, 1.0011, 1.0013, 1.0011, 1.0013],
          [1581512640, 1.0012, 1.0014, 1.0011, 1.0014],
          [1581512700, 1.0014, 1.0017, 1.0012, 1.0017],
          [1581512760, 1.0015, 1.0014, 1.0014, 1.0016],
          [1581512820, 1.0015, 1.0014, 1.0014, 1.0015],
          [1581512880, 1.0015, 1.0015, 1.0013, 1.0015],
          [1581512940, 1.0015, 1.0016, 1.0013, 1.0016],
          [1581513000, 1.0014, 1.0014, 1.0012, 1.0016],
          [1581513060, 1.0014, 1.0014, 1.0014, 1.0015],
          [1581513120, 1.0015, 1.0011, 1.001, 1.0015],
          [1581513180, 1.0012, 1.0011, 1.0011, 1.0013],
          [1581513240, 1.0013, 1.0014, 1.0011, 1.0014],
          [1581513300, 1.0014, 1.0015, 1.0013, 1.0015],
          [1581513360, 1.0015, 1.0015, 1.0014, 1.0016],
          [1581513420, 1.0016, 1.0016, 1.0014, 1.0016],
          [1581513480, 1.0014, 1.0015, 1.0013, 1.0015],
          [1581513540, 1.0015, 1.0013, 1.0012, 1.0015],
          [1581513600, 1.0014, 1.0016, 1.0013, 1.0017],
          [1581513660, 1.0016, 1.0016, 1.0014, 1.0016],
          [1581513720, 1.0015, 1.0015, 1.0014, 1.0016],
          [1581513780, 1.0015, 1.0015, 1.0013, 1.0015],
          [1581513840, 1.0013, 1.0012, 1.0011, 1.0013],
          [1581513900, 1.0012, 1.001, 1.001, 1.0012],
          [1581513960, 1.0012, 1.0014, 1.0011, 1.0014],
          [1581514020, 1.0014, 1.0013, 1.0011, 1.0014],
          [1581514080, 1.0012, 1.0015, 1.0012, 1.0016],
          [1581514140, 1.0015, 1.0016, 1.0014, 1.0016],
          [1581514200, 1.0016, 1.0016, 1.0014, 1.0016],
          [1581514260, 1.0016, 1.0015, 1.0014, 1.0016],
          [1581514320, 1.0015, 1.0016, 1.0015, 1.0017],
          [1581514380, 1.0016, 1.0015, 1.0015, 1.0017],
          [1581514440, 1.0014, 1.0016, 1.0014, 1.0016],
          [1581514500, 1.0016, 1.0014, 1.0014, 1.0016],
          [1581514560, 1.0015, 1.0014, 1.0013, 1.0015],
          [1581514620, 1.0014, 1.0015, 1.0013, 1.0015],
          [1581514680, 1.0015, 1.0015, 1.0014, 1.0016],
          [1581514740, 1.0015, 1.0017, 1.0014, 1.0017],
          [1581514800, 1.0015, 1.0015, 1.0014, 1.0017],
          [1581514860, 1.0015, 1.0015, 1.0014, 1.0016],
          [1581514920, 1.0016, 1.0016, 1.0015, 1.0016],
          [1581514980, 1.0014, 1.0016, 1.0012, 1.0016],
          [1581515040, 1.0015, 1.0017, 1.0015, 1.0017]
        ]
      };
      res = await this.axios.get('http://ncx.aom2008.com/index/api/getkdata', { params: params });
      //console.log(res);
      return this.splitData(res.items);
    },

    getOption(data0) {
      let upColor = "#ec0000";
      let upBorderColor = "#8A0000";
      let downColor = "#00da3c";
      let downBorderColor = "#008F28";

      let option = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross"
          },
          position: [10, 10],
          extraCssText: "opacity: 1;",
          backgroundColor: "#ffffff",

          formatter: function(params, ticket, callback) {
            //console.log("dsfffff", params);

            let html =
              "" +
              "<div>" +
              "<div>" +
              '<span><span style="color: black;">开=</span><span style="color: red;">' +
              params[0].data[1] +
              "</span></span>" +
              '<span><span style="color: black;">高=</span><span style="color: red;">' +
              params[0].data[4] +
              "</span></span>" +
              "</div>" +
              "<div>" +
              '<span><span style="color: black;">低=</span><span style="color: red;">' +
              params[0].data[3] +
              "</span></span>" +
              '<span><span style="color: black;">收=</span><span style="color: red;">' +
              params[0].data[2] +
              "</span></span>" +
              "</div>" +
              "</div>";
            //let res = `<div><div>${params[0].data.description}：${params[0].value} </div><div>日期：${params[0].data.day}</div></div>`;
            return html;
          }
        },

        axisPointer: {
            link: {xAxisIndex: 'all'},
            label: {
                backgroundColor: 'red'
            }
        },

        grid: [
          {
            left: "10%",
            right: "15%",
            height: "50%",
            backgroundColor: "#ccc",
            containLabel: false
          },
          {
            left: "10%",
            right: "15%",
            bottom: "20%",
            height: "15%",
            backgroundColor: "#ccc",
            containLabel: false
          }
        ],

        xAxis: [
          {
            type: "category",
            data: data0.categoryData,
            scale: true,
            boundaryGap: false,

            splitLine: { show: false },
            offset: 120,

            position: "bottom"
          },

          {
            type: "category",
            gridIndex: 1,
            data: data0.categoryData,
            scale: true,
            boundaryGap: false,
            axisLine: { onZero: false },
            axisTick: { show: false },
            splitLine: { show: false },
            axisLabel: { show: false },

            min: "dataMin",
            max: "dataMax",
            position: "bottom"
          }
        ],
        yAxis: [
          {
            position: "right",
            scale: true,
            splitArea: {
              show: false
            },
            splitLine: { show: false }
            
          },
          {
            position: "right",
            scale: true,
            gridIndex: 1,
            splitArea: {
              show: false
            },
            splitLine: { show: false }
          }
        ],
        dataZoom: [
          {
            type: "inside",
            xAxisIndex: [0, 1],
            start: this.dataZoom.start,
            end: this.dataZoom.end
          }
        ],
        series: [
          {
            name: "K线",
            type: "candlestick",
            data: data0.values,
            itemStyle: {
              color: upColor,
              color0: downColor,
              borderColor: upBorderColor,
              borderColor0: downBorderColor
            }
          },
          {
            name: "MA5",
            type: "line",
            data: this.calculateMA(5, data0),
            smooth: true,
            showSymbol: false,
            lineStyle: {
              opacity: 0.5,
              color: '#867e7e',
              normal: {
                width: 1
              }
            }
          },
          {
            name: "MA10",
            type: "line",
            data: this.calculateMA(10, data0),
            smooth: true,
            showSymbol: false,
            lineStyle: {
              opacity: 0.5,
              color: '#eac0c0',
              normal: {
                width: 1
              }
            }
          },
          {
            name: "Volumn",
            type: "bar",
            xAxisIndex: 1,
            yAxisIndex: 1,
            data: data0.volumns,
            itemStyle: {
              normal: {
                color: function(params) {
                  var colorList;
                  if (
                    data0.values[params.dataIndex][1] >
                    data0.values[params.dataIndex][0]
                  ) {
                    colorList = upColor;
                  } else {
                    colorList = downColor;
                  }
                  return colorList;
                }
              }
            }
          }
        ]
      };

      //console.log(option);

      return option;
    },

    formatNumber(n) {
      n = n.toString();
      return n[1] ? n : "0" + n;
    },

    formatTime(number, format) {
      var formateArr = ["Y", "M", "D", "h", "m", "s"];
      var returnArr = [];

      var date = new Date(number * 1000);
      returnArr.push(date.getFullYear());
      returnArr.push(this.formatNumber(date.getMonth() + 1));
      returnArr.push(this.formatNumber(date.getDate()));

      returnArr.push(this.formatNumber(date.getHours()));
      returnArr.push(this.formatNumber(date.getMinutes()));
      returnArr.push(this.formatNumber(date.getSeconds()));

      for (var i in returnArr) {
        format = format.replace(formateArr[i], returnArr[i]);
      }
      return format;
    },

    ask(url, params, method) {
      let baseUrl = "http://ncx.aom2008.com/index/";
      let axios = this.axios;
      if (method == "get") {
        return axios.get(baseUrl + url, { params: params }).then(data => {
          return data.data;
        });
      } else if (method == "post") {
        return axios
          .post(baseUrl + url, params, {
            headers: {
              "content-type": "application/json"
            }
          })
          .then(data => {
            return data.data;
          });
      } else {
        console.log("请求方式有问题");
      }
    },

    zoomClick() {

      console.log("zoomClick")

      let  direction = this.dataZoom.direction;
      if (1 == direction) {
        this.dataZoom.start = this.dataZoom.start + 3;
        this.dataZoom.end = this.dataZoom.end - 3;
        this.dataZoom.startValue = this.dataZoom.startValue + 2;
        this.dataZoom.endValue = this.dataZoom.endValue - 2;
      }

      this.myeChart.dispatchAction({
        type: "dataZoom",
        
        dataZoomIndex: 0,
        // 开始位置的百分比，0 - 100
        start: this.dataZoom.start,
        // 结束位置的百分比，0 - 100
        end: this.dataZoom.end,
        // 开始位置的数值
        startValue: this.dataZoom.startValue,
        // 结束位置的数值
        endValue: this.dataZoom.endValue
      });
    }
  }
};
</script>

<style scoped>
.enlarge img{
    display: inline-block;
    width: 1.875rem;
    height: 1.875rem;
    position: relative;
    right: 41%;
    top: 1.25rem;
  }
  /deep/ .van-tabs__wrap--scrollable .van-tab {
    -webkit-box-flex: 0;
    -ms-flex: 0 0 0%;
    flex: 1 0 0% !important;
}

</style>